package com.jstyle.beatecg.fragment;

import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.jstyle.beatecg.R;
import com.jstyle.beatecg.daoManager.PathRecordDaoManager;
import com.jstyle.beatecg.model.HrvData;
import com.jstyle.beatecg.model.PathRecord;
import com.jstyle.beatecg.util.ChartDataUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindArray;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import lecho.lib.hellocharts.model.Axis;
import lecho.lib.hellocharts.model.Viewport;
import lecho.lib.hellocharts.view.AbstractChartView;
import lecho.lib.hellocharts.view.LineChartView;


/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link ExerciseHistoryFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class ExerciseHistoryFragment extends Fragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    @BindView(R.id.history_linechart_distance)
    LineChartView historyLinechartDistance;
    @BindView(R.id.history_linechart_time)
    LineChartView historyLinechartTime;
    @BindView(R.id.history_linechart_heart)
    LineChartView historyLinechartHeart;
    @BindArray(R.array.week)
    String[] arrayWeek;
    Unbinder unbinder;
    private static final String TAG = "ExerciseHistoryFragment";
    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;

    public ExerciseHistoryFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment ExerciseHistoryFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static ExerciseHistoryFragment newInstance(String param1, String param2) {
        ExerciseHistoryFragment fragment = new ExerciseHistoryFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_exercise_history, container, false);
        unbinder = ButterKnife.bind(this, view);
        initView();
        return view;
    }

    private void initView() {
        String[] axisArray = getAxiesArray();
        int length=axisArray.length;
        if(length==1){
            updateDayChart(axisArray);
        }else{
            updateWeekOrMonthChart(axisArray,length);
        }


    }

    private void updateWeekOrMonthChart(String[] axisArray, int length) {
        List<PathRecord>pathRecordList= PathRecordDaoManager.getPathRecord(axisArray[0],axisArray[length-1]);
        HashMap<String,List<String>>distanceHashMap=new HashMap<>();
        HashMap<String,List<String>>timeHashMap=new HashMap<>();
        HashMap<String,List<String>>heartHashMap=new HashMap<>();
        for(PathRecord pathRecord:pathRecordList){
            String date=pathRecord.getMDate().split(" ")[0];
            String duration=pathRecord.getMDuration();
            String distance=pathRecord.getDistanceBeat();
            String heart=pathRecord.getHeartListString();
            List<String>distanceList=distanceHashMap.get(date);
            if(distanceList==null){
                distanceList=new ArrayList<>();
            }
            distanceList.add(distance);
            distanceHashMap.put(date,distanceList);
            List<String>durationList=timeHashMap.get(date);
            if(durationList==null){
                durationList=new ArrayList<>();
            }
            durationList.add(duration);
            timeHashMap.put(date,durationList);
            List<String>heartList=heartHashMap.get(date);
            if(heartList==null){
                heartList=new ArrayList<>();
            }
            heartList.add(heart);
            heartHashMap.put(date,heartList);

        }
        ChartDataUtil.initChartView(historyLinechartDistance,-0.5f,22,length-0.5f,0);
        ChartDataUtil.initChartView(historyLinechartTime,-0.5f,380,length-0.5f,0);
        ChartDataUtil.initChartView(historyLinechartHeart,-0.5f,170,length-0.5f,30);
        historyLinechartDistance.setLineChartData(ChartDataUtil.getDistanceChart(getActivity(),axisArray,distanceHashMap));
        historyLinechartTime.setLineChartData(ChartDataUtil.getTimeChart(getActivity(),axisArray,timeHashMap));
        historyLinechartHeart.setLineChartData(ChartDataUtil.getHeartChart(getActivity(),axisArray,heartHashMap));
    }



    private void updateDayChart(String[] axisArray) {
        List<PathRecord>pathRecordList= PathRecordDaoManager.getPathRecord(axisArray[0],axisArray[0]);
        ChartDataUtil.initChartView(historyLinechartDistance,-0.5f,5.5f,pathRecordList.size(),0);
        ChartDataUtil.initChartView(historyLinechartTime,-0.5f,380,pathRecordList.size(),0);
        ChartDataUtil.initChartView(historyLinechartHeart,0f,170,pathRecordList.size(),30);

        historyLinechartDistance.setLineChartData(ChartDataUtil.getDistanceDayChart(getActivity(),pathRecordList));
        historyLinechartTime.setLineChartData(ChartDataUtil.getTimeDayChart(getActivity(),pathRecordList));
        historyLinechartHeart.setLineChartData(ChartDataUtil.getHeartDayChart(getActivity(),pathRecordList));

    }


    @Override
    public void setMenuVisibility(boolean menuVisible) {
        super.setMenuVisibility(menuVisible);
        if (this.getView() != null) {
            this.getView().setVisibility(menuVisible ? View.VISIBLE : View.GONE);
            if(menuVisible&&isAdded())initView();
        }
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
//        if (context instanceof OnFragmentInteractionListener) {
//            mListener = (OnFragmentInteractionListener) context;
//        } else {
//            throw new RuntimeException(context.toString()
//                    + " must implement OnFragmentInteractionListener");
//        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
    public void updateData() {
        if(isVisible()) initView();
    }
    private String[] getAxiesArray() {
        InfoFragment infoFragment = (InfoFragment) getParentFragment();
        int dateType = infoFragment.dateType;
        String[] axisArray = null;
        switch (dateType) {
            case 0:
                axisArray=new String[1];
                axisArray[0]=infoFragment.getTodayString();
                break;
            case 1:
                axisArray = infoFragment.getThisWeek();
                break;
            case 2:
                axisArray = infoFragment.getMonthDate();
                break;
        }
        return axisArray;
    }

}
